package com.lagou.encode;

import com.lagou.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class RpcDecoder extends ByteToMessageDecoder {
    private Class<?> clazz;
    private Serializer serializer;
    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // out.add(in.)
        System.out.println("解码开始");
        if (in.readableBytes() < 4){
            return;
        }
        in.markReaderIndex();
        int readInt = in.readInt();
        if (in.readableBytes() < readInt){
            in.resetReaderIndex();
            return;
        }
        // 调用工具类的反序列化方法
        byte[] bytes = new byte[readInt];
        in.readBytes(bytes);
        Object object = serializer.deserialize(clazz,bytes);
        out.add(object);
    }
}
